package com.dc.util;

import org.junit.Test;
import org.springframework.util.DigestUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
    //盐值，加大撞库破解难度，可用随机数，可把盐放加密后的字符串前以便下次验证取盐
    private static String salt = "dc6";
    /**
     * MD5加密类
     * @param str 要加密的字符串
     * @return    加密后的字符串
     */
    public static String code(String str){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update((str+salt).getBytes());
            byte[]byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }



    @Test
    public void test1(){
        String pwd = "111";
        String pwdsalt = pwd+salt;
        System.out.println(MD5Utils.code(pwd));//02ea75559f545c6e532db05164cd8541
    }
    public static void main(String[] args) {
        String pwd = "111";
        String pwdsalt = pwd+salt;
        System.out.println(MD5Utils.code(pwd));
        System.out.println(DigestUtils.md5DigestAsHex(pwdsalt.getBytes()));
    }
}
